import React, { useState } from 'react'
import type { MenuProps } from 'antd'
import { Menu } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'
import routeConfig from '@/router/index'
import type { MyRouteObject } from '@/router/routerType'
import { authority } from '@/assets/dict/authCode'

interface MenuType {
  key: string | undefined
  icon: React.ReactNode | undefined
  children: MyRouteObject[] | undefined
  label: string | undefined
  type?: string
}

const leftMenu: React.FC = () => {
  
  const routers: MyRouteObject[] = routeConfig[0].children as MyRouteObject[]
  function routerToMenu(list: MyRouteObject[]): MenuType[] {
    return list.filter((item) => {
      return item.inMenu && authority(item?.path || '')
    }).map((item) => {
      return {
        key: item.path,
        icon: item.icon,
        children: item.children && routerToMenu(item.children),
        label: item.title
      }
    })
  }
  
  const MenuItems = routerToMenu(routers) as MenuProps['items']
  const navigate = useNavigate()
  const onClick: MenuProps['onClick'] = ({ keyPath }) => {
    const paths: string[] = keyPath.reverse()
    navigate(paths.join('/'))
  }
  const location = useLocation()
  const pathName = location.pathname
  const [defaultSelectedKeys] = useState(pathName.split('/'))

  return (
    <Menu
      onClick={onClick}
      style={{ width: 256 }}
      defaultSelectedKeys={defaultSelectedKeys}
      defaultOpenKeys={defaultSelectedKeys}
      mode="inline"
      items={MenuItems}
    />
  )
}

export default leftMenu